package com.juyu.miliao.scheduler.handler;

import com.alibaba.fastjson.JSONObject;
import com.juyu.miliao.common.delay.DelayMessage;
import com.juyu.miliao.scheduler.service.VipExpireService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import java.util.concurrent.DelayQueue;

/**
 * @author xuanqicheng
 */
public class VipExpireQueueThread implements Runnable {

    private Logger logger = LoggerFactory.getLogger(VipExpireQueueThread.class);

    private VipExpireService vipExpireService;

    /**
     * 延时队列 ,消费者从其中获取消息进行消费
     */
    private DelayQueue<DelayMessage> queue;


    public VipExpireQueueThread(VipExpireService vipExpireService) {
        this.vipExpireService = vipExpireService;
        this.queue = vipExpireService.getVipExpireQueueInit();
    }

    @Override
    public void run() {
        while (true) {
            try {
                DelayMessage<Integer> take = queue.take();
                logger.info("处理延迟任务"+ JSONObject.toJSONString(take));
                vipExpireService.vipExpireDataHandler(take);
            } catch (Exception e) {
                logger.info("处理延迟任务错误："+e.getMessage());
            }
        }
    }

    public void put(DelayMessage delayMessage){
        queue.offer(delayMessage);
    }
}
